package com.wzc.chatserver;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.Socket;

public class ClientApplication {
    // 创建Socket对象，指定服务端的IP地址和端口号
    public static Socket socket;

    // 获取输入流和输出流 输入流和输出流是通过socket对象来进行数据传输的。
    public static BufferedReader in;

    public static PrintWriter out;

    static String[] option = {"用户1（端口54088）", "用户2（端口58840）"};

    static int port = JOptionPane.showOptionDialog(null,
            "请选择你的用户身份，必须用户1和用户2同时在线才可聊天，且只能有一个用户1,一个用户2",
            "选择端口",
            JOptionPane.DEFAULT_OPTION,
            JOptionPane.PLAIN_MESSAGE,
            null,
            option,
            option[0]);



    static {
        try {
            if (port == 0){
                port = 54088;
            } else if (port == 1) {
                port = 58840;
            }
            socket = new Socket("127.0.0.1", port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException | IllegalArgumentException e) {
            JOptionPane.showMessageDialog(null, "错误");
            System.exit(1);
        }
    }

    public static String message = "null";
    public static class ChatWindow {
        static JTextField jt=new JTextField(20);
        public static  JTextArea sArea=new JTextArea(15,20);
        public static String content;
        public static void createChat(){
            //1.窗口
            JFrame jf=new JFrame("聊天窗口");
            jf.setLayout(new BorderLayout());
            jf.setSize(600,320);
            jf.setLocation(300,400);
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jf.setVisible(true);
            //创建文本域

            //2.带滚动条的面板容器
            JScrollPane scrollPane=new JScrollPane(sArea);
            sArea.setEditable(false);//文本域不可编辑
            //3创建中间容器，放3各组件
            JPanel jp=new JPanel();
            JLabel jl=new JLabel("请输入聊天信息");
            JButton jb=new JButton("发送（Enter）");

            jb.addActionListener(e -> {
                content=jt.getText();
                if(content!=null && !content.trim().isEmpty()){
                    message = content;
                    sArea.append("\n" + content+"\n");
                    sArea.setCaretPosition(sArea.getText().length());
                    out.println(message);
                }else {
                    sArea.append("聊天信息不能为空！！！"+"\n");
                    sArea.setCaretPosition(sArea.getText().length());
                }
                jt.setText("");
                sArea.setCaretPosition(sArea.getText().length());
            });

            jt.addKeyListener(new KeyAdapter() {
                @Override
                public void keyReleased(KeyEvent e) {
                    super.keyReleased(e);
                    int s = e.getKeyCode();
                    if (s == '\n'){
                        content=jt.getText();
                        if(content!=null && !content.trim().isEmpty()){
                            message = content;
                            sArea.append("\n" + content+"\n");
                            sArea.setCaretPosition(sArea.getText().length());
                            out.println(message);
                        }else {
                            sArea.append("聊天信息不能为空！！！"+"\n");
                            sArea.setCaretPosition(sArea.getText().length());
                        }
                        jt.setText("");
                        sArea.setCaretPosition(sArea.getText().length());
                    }
                }
            });
            WindowAdapter window = new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    super.windowClosed(e);
                    try {
                        out.println("xzijbczxchihiuxchiuh呼吸组赤髭须和从自uhzihczihcziuzhcizxhhzixchweuqpgfsgygvzpgpzgv");
                        socket.close();
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(null, "错误");
                        System.exit(1);
                    }
                }
            };
            jf.addWindowListener(window);
            jp.add(jl);
            jp.add(jt);
            jp.add(jb);
            jf.add(jp,BorderLayout.PAGE_END);
            jf.add(scrollPane,BorderLayout.PAGE_START);
        }

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(ChatWindow::createChat);
        ChatWindow.sArea.append("dnbmc工作室\n");
        while(true){
            String response = "";
            try {
                response = in.readLine();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "错误");
                System.exit(1);
            }
            if (response == null){
                ChatWindow.sArea.append("\n服务端无响应，请退出。\n");
                break;
            }
            ChatWindow.sArea.append("服务端消息：" + response + "\n");
            ChatWindow.sArea.setCaretPosition(ChatWindow.sArea.getText().length());
        }
    }
}
